package com.zhangxin.aiInterview.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.manager.work_flow.debug_code.DebugCode;
import com.zhangxin.aiInterview.manager.work_flow.exam_analyze.ExamAnalyze;
import com.zhangxin.aiInterview.manager.work_flow.generate_exam.ExamGenerate;
import com.zhangxin.aiInterview.manager.work_flow.search_same_type_programing_info.SearchSameTypeProgramingInfo;
import com.zhangxin.aiInterview.manager.knoewlege_base_api.ExamQuestionParser;
import com.zhangxin.aiInterview.manager.knoewlege_base_api.dto.ExamQuestionWrapper;
import com.zhangxin.aiInterview.manager.xfapi.http.GenerateExamQuestionApi;
import com.zhangxin.aiInterview.manager.xfapi.http.GenerateExamQuestionDeepSeekApi;
import com.zhangxin.aiInterview.mapper.ExamMapper;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.model.enums.AnalyzeStatusEnum;
import com.zhangxin.aiInterview.model.enums.InterviewRoleEnum;
import com.zhangxin.aiInterview.model.enums.IsFullInterviewEnum;
import com.zhangxin.aiInterview.model.vo.response.DebugCodeResponse;
import com.zhangxin.aiInterview.model.vo.response.GetExamAnalyzeResultResponse;
import com.zhangxin.aiInterview.model.vo.response.PartQuestionCountResponse;
import com.zhangxin.aiInterview.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @author ZX
 * @description 针对表【exam(笔试)】的数据库操作Service实现
 * @createDate 2025-04-25 14:58:29
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam>
        implements ExamService {
    @Resource
    private ExamContentService examContentService;
    @Resource
    private UserService userService;
    @Resource
    private PositionService positionService;
    @Resource
    private GenerateExamQuestionApi generateExamQuestionApi;
    @Resource
    private FullProcessInterviewService fullProcessInterviewService;
    @Resource
    private ExamAnalysisResultService examAnalysisResultService;
    @Resource
    private FullProcessAnalyzeResultService fullProcessAnalyzeResultService;
    @Resource
    private CompanyService companyService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private ExamKnowledgeBaseService examKnowledgeBaseService;
    @Resource
    private TechFieldService techFieldService;

    /**
     * 基于知识库生成笔试题
     *
     * @param techFieldId     领域id
     * @param positionId      职位id
     * @param companyId       公司id
     * @param isFull          是否为全流程面试
     * @param fullInterviewId 全流程面试id
     * @param request
     */
    @Override
    @Transactional
    public Long generateExam(Long techFieldId, Long positionId, Long companyId, HttpServletRequest request,
                             Boolean isFull, Long fullInterviewId) {
        Long userId = userService.getLoginUser(request).getId();
        Integer userInterviewRole = userService.getUserInterviewRole(request);
        Position position = positionService.getById(positionId);
        String company = companyService.getById(companyId).getName();
        TechField techField = techFieldService.getById(techFieldId);

        // 上传当前笔试内容
        Exam exam = new Exam();
        exam.setUserId(userId);
        exam.setPositionId(positionId);
        exam.setPosition(position.getName());
        exam.setCompany(company);
        exam.setExamStatus(AnalyzeStatusEnum.UNFINISHED.getValue());
        if (isFull) {
            exam.setIsFull(IsFullInterviewEnum.FULL_INTERVIEW.getValue());
        } else {
            exam.setIsFull(IsFullInterviewEnum.IS_NOT_FULL_INTERVIEW.getValue());
        }
        // 保存
        save(exam);

        // 判断是否为全流程面试
        if (isFull) {
            // 回写笔试id
            fullProcessInterviewService.lambdaUpdate()
                    .eq(FullProcessInterview::getId, fullInterviewId)
                    .set(FullProcessInterview::getExamId, exam.getId())
                    .update();
        }

        InterviewRoleEnum interviewRoleEnum = InterviewRoleEnum.getEnumByValue(userInterviewRole);
        if (interviewRoleEnum == null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有当前这个面试身份");
        long start = System.currentTimeMillis();
        try {
            Long examId = exam.getId();
            // deepSeek生成笔试题目
            String examQuestionsJsonStr = GenerateExamQuestionDeepSeekApi.generateExamQuestion(position.getName(),
                    interviewRoleEnum.getText(), company);
            // 讯飞大模型生成笔试题目
//            String examQuestionsJsonStr = generateExamQuestionApi.getExamQuestions(position.getName(),
//                    interviewRoleEnum.getText(), company);
            // 工作流根据真实题库生成笔试题目
            // ExamKnowledgeBase examKnowledgeBase = examKnowledgeBaseService.lambdaQuery()
            // .eq(ExamKnowledgeBase::getCompany, company)
            // .eq(ExamKnowledgeBase::getTechFieldName, techField.getName())
            // .eq(ExamKnowledgeBase::getPositionName, position.getName())
            // .one();
            // String examQuestionsJsonStr =
            // ExamGenerate.generateExam(examKnowledgeBase.getFileId());

            long end = System.currentTimeMillis();
            log.info("获取笔试题目耗时：" + (end - start));
            log.info("笔试id" + examId);
            // 上传笔试内容
            ExamContent examContent = new ExamContent();
            examContent.setExamId(examId);
            examContent.setUserId(userId);
            examContent.setQuestionList(examQuestionsJsonStr);
            examContentService.save(examContent);
            // 返回题目id
            return examId;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, e.getMessage());
        }
    }

    /**
     * 根据笔试id查询题目
     *
     * @param examId
     * @param request
     * @return
     */
    @Override
    public ExamQuestionWrapper getQuestion(Long examId, HttpServletRequest request) {
        ExamContent examContent = examContentService.lambdaQuery()
                .eq(ExamContent::getExamId, examId)
                .one();
        String questionList = examContent.getQuestionList();
        return ExamQuestionParser.parseExamQuestions(questionList);
    }

    /**
     * 调试代码
     *
     * @param codeModel
     * @return
     */
    @Override
    public DebugCodeResponse debugCode(String codeModel) {
        String result = DebugCode.debugCode(codeModel);
        // 匹配开头的```json，以及结尾的```}
        result = result.replaceAll("^```json|```}$", "");
        return JSONUtil.toBean(result, DebugCodeResponse.class);
    }

    @Override
    public PartQuestionCountResponse getPartQuestionCount(Long examId) {
        // 查询考试内容
        ExamContent examContent = examContentService.lambdaQuery()
                .eq(ExamContent::getExamId, examId)
                .one();

        // 获取题目列表JSON字符串
        String questionList = examContent.getQuestionList();
        questionList = questionList
                .replaceFirst("^\\s*```json\\s*", "") // 去除开头的 ```json 和可能的换行
                .replaceFirst("\\s*```\\s*$", ""); // 去除结尾的 ``` 和可能的换行

        // 使用 Hutool 解析JSON数组
        JSONArray questionArray = JSONUtil.parseArray(questionList);

        // 初始化统计变量
        int choiceCount = 0;
        int shortAnswerCount = 0;
        int programmingCount = 0;

        // 遍历题目类型
        for (int i = 0; i < questionArray.size(); i++) {
            JSONObject questionType = questionArray.getJSONObject(i);
            int type = questionType.getInt("type");
            JSONArray questions = questionType.getJSONArray("question");

            // 根据类型统计
            switch (type) {
                case 1:
                    choiceCount += questions.size();
                    break;
                case 2:
                    shortAnswerCount += questions.size();
                    break;
                case 3:
                    programmingCount += questions.size();
                    break;
                default:
                    log.warn("未知题目类型: {}", type);
            }
        }

        // 封装响应对象
        PartQuestionCountResponse response = new PartQuestionCountResponse();
        response.setChoiceCount(choiceCount);
        response.setShortAnswerCount(shortAnswerCount);
        response.setProgrammingCount(programmingCount);

        return response;
    }

    /**
     * 异步分析笔试结果
     *
     * @param userId
     * @param examId
     * @param examDuration
     * @param answers
     * @param isFull
     * @param fullInterviewId
     * @return
     */
    @Override
    @Transactional
    public boolean analyzeExamResult(Long userId, Long examId, Integer examDuration, String answers, Boolean isFull,
            Long fullInterviewId) {

        // 保存笔试时间和笔试分析状态
        lambdaUpdate()
                .set(Exam::getExamDuration, examDuration)
                .set(Exam::getExamStatus, AnalyzeStatusEnum.ANALYZING.getValue())
                .eq(Exam::getId, examId)
                .update();
        // 保存用户笔试答案
        boolean update = examContentService.lambdaUpdate()
                .set(ExamContent::getUserAnswers, answers)
                .eq(ExamContent::getExamId, examId)
                .update();
        if (!update)
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "笔试结果更新失败");

        // 异步分析笔试结果
        CompletableFuture.runAsync(() -> {
            try {
                // 修改笔试分析状态
                lambdaUpdate()
                        .set(Exam::getExamStatus, AnalyzeStatusEnum.ANALYZING.getValue())
                        .eq(Exam::getId, examId)
                        .update();

                // 获取题目列表和用户答案
                ExamContent examContent = examContentService.lambdaQuery()
                        .eq(ExamContent::getExamId, examId)
                        .one();
                String questionListStr = examContent.getQuestionList();
                String userAnswersStr = examContent.getUserAnswers();

                // 清理JSON格式
                questionListStr = questionListStr
                        .replaceFirst("^\\s*```json\\s*", "")
                        .replaceFirst("\\s*```\\s*$", "");

                // 解析题目列表和用户答案
                JSONArray questionList = JSONUtil.parseArray(questionListStr);
                JSONArray userAnswers = JSONUtil.parseArray(userAnswersStr);

                // 1. 编写代码判断选择题
                JSONObject choiceResult = analyzeChoiceQuestions(questionList, userAnswers);
                System.out.println("选择题判题结果: " + choiceResult);

                // 2. 使用AI工作流分析问答题和编程题
                String aiAnalyzeResult = ExamAnalyze.analyzeExam(userId, examId);
                System.out.println("问答题和编程题判题结果: " + aiAnalyzeResult);

                // 3. 整合所有结果
                JSONObject finalResult = new JSONObject();
                finalResult.set("out1", choiceResult);

                // 解析AI分析结果并添加
                JSONObject aiResult = JSONUtil.parseObj(aiAnalyzeResult);
                if (aiResult.containsKey("out2")) {
                    finalResult.set("out2", aiResult.getJSONObject("out2"));
                }
                if (aiResult.containsKey("out3")) {
                    finalResult.set("out3", aiResult.getJSONObject("out3"));
                }
                String analyzeContent = finalResult.toString();
                System.out.println("最终结果: " + analyzeContent);

                // 计算笔试总分
                Integer totalScores = calculateTotalScore(analyzeContent);
                System.out.println("笔试总分: " + totalScores);

                ExamAnalysisResult examAnalysisResult = new ExamAnalysisResult();

                // 获取编程题错题题目
                List<String> list = extractQuestionTitlesFromOut3(analyzeContent);
                // 如果编程题没有错题则不执行
                if (!list.isEmpty()) {
                    // 创建异步任务集合
                    List<CompletableFuture<String>> futures = new ArrayList<>();
                    for (String questionTitle : list) {
                        // 异步执行搜索，并将任务加入列表
                        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                            String jsonStr = SearchSameTypeProgramingInfo.search(questionTitle);
                            return jsonStr.replaceAll("^```json\\s*|```$", "").trim();
                        });
                        futures.add(future);
                    }
                    // 等待所有异步任务完成
                    CompletableFuture<Void> allDone = CompletableFuture
                            .allOf(futures.toArray(new CompletableFuture[0]));
                    allDone.join();
                    // 收集所有任务的返回结果
                    List<String> results = futures.stream()
                            .map(future -> {
                                try {
                                    return future.get(); // 获取每个任务结果
                                } catch (InterruptedException | ExecutionException e) {
                                    throw new BusinessException(ErrorCode.OPERATION_ERROR,
                                            "搜索结果获取失败:" + e.getMessage());
                                }
                            })
                            .filter(result -> result != null && !result.isEmpty()) // 过滤无效结果
                            .collect(Collectors.toList());
                    // 将结果写入数据库
                    examAnalysisResult.setWrongProgramingUrl(results.toString());
                    System.out.println("编程题错题讲解: " + results);
                }

                // 2. 将分析结果写入数据库
                examAnalysisResult.setUserId(userId);
                examAnalysisResult.setExamId(examId);
                examAnalysisResult.setContent(analyzeContent);
                examAnalysisResult.setTotalScores(totalScores);

                examAnalysisResultService.save(examAnalysisResult);

                // 判断是否为全流程面试(回写笔试分析id)
                if (isFull) {
                    fullProcessAnalyzeResultService.lambdaUpdate()
                            .eq(FullProcessAnalyzeResult::getFullInterviewId, fullInterviewId)
                            .set(FullProcessAnalyzeResult::getWrittenTestAnalysisId, examAnalysisResult.getId())
                            .update();
                }

                // 3. 更新笔试状态，绑定简历分析id
                lambdaUpdate()
                        .set(Exam::getExamStatus, AnalyzeStatusEnum.COMPLETED.getValue())
                        .set(Exam::getExamResultId, examAnalysisResult.getId())
                        .eq(Exam::getId, examId)
                        .update();

            } catch (Exception e) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, e.getMessage());
            }
        }).exceptionally(ex -> {
            log.error("异步分析笔试结果失败", ex);
            return null;
        });
        return true;
    }

    /**
     * 自动判断选择题
     *
     * @param questionList 题目列表
     * @param userAnswers  用户答案列表
     * @return 选择题判题结果
     */
    private JSONObject analyzeChoiceQuestions(JSONArray questionList, JSONArray userAnswers) {
        JSONObject result = new JSONObject();
        JSONArray wrongQuestions = new JSONArray();

        // 找到选择题部分
        JSONObject choiceSection = null;
        for (int i = 0; i < questionList.size(); i++) {
            JSONObject section = questionList.getJSONObject(i);
            if (section.getInt("type") == 1) { // type=1表示选择题
                choiceSection = section;
                break;
            }
        }

        if (choiceSection == null) {
            // 没有选择题
            result.set("score", 0);
            result.set("total_questions", 0);
            result.set("correct_count", 0);
            result.set("wrong_count", 0);
            result.set("wrong_questions", wrongQuestions);
            return result;
        }

        JSONArray questions = choiceSection.getJSONArray("question");
        int totalQuestions = questions.size();
        int correctCount = 0;
        int wrongCount = 0;

        // 遍历用户答案，找到选择题的答案
        int choiceAnswerIndex = 0;
        for (int i = 0; i < userAnswers.size(); i++) {
            JSONObject userAnswer = userAnswers.getJSONObject(i);
            if ("choice".equals(userAnswer.getStr("type"))) {
                if (choiceAnswerIndex < questions.size()) {
                    JSONObject question = questions.getJSONObject(choiceAnswerIndex);
                    String userAnswerValue = userAnswer.getStr("userAnswer");

                    // 从题目中直接读取正确答案
                    String correctAnswer = question.getStr("correct_answer");
                    String correctAnswerContent = question.getStr("correct_answer_content");

                    if (correctAnswer != null && correctAnswer.equals(userAnswerValue)) {
                        correctCount++;
                    } else {
                        wrongCount++;
                        // 添加到错题列表
                        JSONObject wrongQuestion = new JSONObject();
                        wrongQuestion.set("questionTitle", question.getStr("title"));
                        wrongQuestion.set("user_answer", userAnswerValue);
                        wrongQuestion.set("user_answer_content", getOptionContent(question, userAnswerValue));
                        wrongQuestion.set("correct_answer", correctAnswer);
                        wrongQuestion.set("correct_answer_content", correctAnswerContent);
                        wrongQuestions.add(wrongQuestion);
                    }
                }
                choiceAnswerIndex++;
            }
        }

        // 计算得分，每题2分
        int score = correctCount * 2;

        result.set("score", score);
        result.set("total_questions", totalQuestions);
        result.set("correct_count", correctCount);
        result.set("wrong_count", wrongCount);
        result.set("wrong_questions", wrongQuestions);

        return result;
    }

    /**
     * 根据选项key获取选项内容
     */
    private String getOptionContent(JSONObject question, String key) {
        JSONArray options = question.getJSONArray("option");
        for (int i = 0; i < options.size(); i++) {
            JSONObject option = options.getJSONObject(i);
            if (key.equals(option.getStr("key"))) {
                return option.getStr("value");
            }
        }
        return "";
    }

    /**
     * 获取笔试分析结果(封装为java对象)
     *
     * @param examId
     * @return
     */
    @Override
    public GetExamAnalyzeResultResponse getExamAnalyzeResult(Long examId) {

        // 获取笔试题分析结果
        ExamAnalysisResult examAnalysisResult = examAnalysisResultService.lambdaQuery()
                .eq(ExamAnalysisResult::getExamId, examId)
                .one();
        if (examAnalysisResult == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "笔试结果不存在");
        }

        // 解析 JSON 字符串
        String jsonStr = examAnalysisResult.getContent();

        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(jsonStr);

        // 选择题部分
        com.alibaba.fastjson.JSONObject structured1 = jsonObject.getJSONObject("out1");
        GetExamAnalyzeResultResponse.Choices choices = new GetExamAnalyzeResultResponse.Choices();
        choices.setTotalScore(structured1.getInteger("score"));

        List<GetExamAnalyzeResultResponse.Choice> choiceList = structured1.getJSONArray("wrong_questions")
                .toJavaList(com.alibaba.fastjson.JSONObject.class)
                .stream().map(obj -> {
                    GetExamAnalyzeResultResponse.Choice c = new GetExamAnalyzeResultResponse.Choice();
                    c.setQuestionTitle(obj.getString("questionTitle"));
                    c.setUser_answer(obj.getString("user_answer"));
                    c.setUser_answer_content(obj.getString("user_answer_content"));
                    c.setCorrect_answer(obj.getString("correct_answer"));
                    c.setCorrect_answer_content(obj.getString("correct_answer_content"));
                    return c;
                }).collect(Collectors.toList());
        choices.setList(choiceList);

        // 问答题部分
        com.alibaba.fastjson.JSONObject structured2 = jsonObject.getJSONObject("out2");
        GetExamAnalyzeResultResponse.ShortAnswers shortAnswers = new GetExamAnalyzeResultResponse.ShortAnswers();

        // 获取 questions 数组
        List<com.alibaba.fastjson.JSONObject> questionList = structured2.getJSONArray("questions")
                .toJavaList(com.alibaba.fastjson.JSONObject.class);

        // 遍历每一题，封装成 ShortAnswer 对象
        int shortAnswerTotalScore = 0;
        List<GetExamAnalyzeResultResponse.ShortAnswer> shortAnswerList = new ArrayList<>();

        for (com.alibaba.fastjson.JSONObject obj : questionList) {
            GetExamAnalyzeResultResponse.ShortAnswer sa = new GetExamAnalyzeResultResponse.ShortAnswer();
            sa.setQuestionTitle(obj.getString("questionTitle"));
            sa.setScore(obj.getInteger("score"));
            sa.setUser_answer(obj.getString("user_answer"));
            sa.setCorrect_answer(obj.getString("correct_answer"));
            shortAnswerList.add(sa);

            shortAnswerTotalScore += sa.getScore() != null ? sa.getScore() : 0;
        }

        shortAnswers.setList(shortAnswerList);
        shortAnswers.setTotalScore(shortAnswerTotalScore);

        // 编程题部分
        com.alibaba.fastjson.JSONObject structured3 = jsonObject.getJSONObject("out3");
        GetExamAnalyzeResultResponse.Programmings programmings = new GetExamAnalyzeResultResponse.Programmings();
        programmings.setTotalScore(structured3.getInteger("score"));

        List<GetExamAnalyzeResultResponse.Programming> programmingList = structured3.getJSONArray("wrong_questions")
                .toJavaList(com.alibaba.fastjson.JSONObject.class)
                .stream().map(obj -> {
                    GetExamAnalyzeResultResponse.Programming p = new GetExamAnalyzeResultResponse.Programming();
                    p.setQuestionTitle(obj.getString("questionTitle"));
                    p.setUser_answer(obj.getString("user_answer"));
                    p.setCorrect_answer(obj.getString("correct_answer"));
                    return p;
                }).collect(Collectors.toList());
        programmings.setList(programmingList);

        // 封装最终结果
        GetExamAnalyzeResultResponse response = new GetExamAnalyzeResultResponse();
        response.setChoices(choices);
        response.setShortAnswers(shortAnswers);
        response.setProgrammings(programmings);

        return response;
    }

    /**
     * 公共接口：根据公司、岗位、面试角色生成笔试题
     * 直接调用AI接口生成题目，不保存到数据库
     *
     * @param company 公司名称
     * @param position 岗位名称
     * @param interviewRole 面试角色
     * @return 生成的笔试题内容
     */
    @Override
    public String publicGenerateExam(String company, String position, String interviewRole) {
        try {
            log.info("开始生成公共笔试题：公司={}, 岗位={}, 面试角色={}", company, position, interviewRole);
            
            // 使用DeepSeek API生成笔试题
            String examQuestionsJsonStr = GenerateExamQuestionDeepSeekApi.generateExamQuestion(
                    position, interviewRole, company);
            
            // 清理JSON格式
            examQuestionsJsonStr = examQuestionsJsonStr
                    .replaceFirst("^\\s*```json\\s*", "")
                    .replaceFirst("\\s*```\\s*$", "");
            
            log.info("公共笔试题生成成功");
            return examQuestionsJsonStr;
            
        } catch (Exception e) {
            log.error("公共笔试题生成失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "生成笔试题失败：" + e.getMessage());
        }
    }

    /**
     * 删除笔试记录
     * 
     * @param examId
     * @param request
     * @return
     */
    @Override
    public boolean deleteExam(Long examId, HttpServletRequest request) {
        // 开启方法事务
        transactionTemplate.execute(status -> {
            try {
                // 删除笔试记录
                removeById(examId);

                // 删除笔试内容
                QueryWrapper<ExamContent> examContentQueryWrapper = new QueryWrapper<>();
                examContentQueryWrapper.eq("examId", examId);
                examContentService.remove(examContentQueryWrapper);

                // 删除笔试分析结果
                QueryWrapper<ExamAnalysisResult> examAnalysisResultQueryWrapper = new QueryWrapper<>();
                examAnalysisResultQueryWrapper.eq("examId", examId);
                examAnalysisResultService.remove(examAnalysisResultQueryWrapper);

            } catch (Exception e) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,
                        "删除笔试记录相关信息失败，id为::" + examId + "，报错信息" + e.getMessage());
            }
            return null;
        });
        return true;
    }

    /**
     * 从给定 JSON 字符串中提取 out3.wrong_questions 数组中的所有 questionTitle 字段
     * 并将其存储到一个 Set<String> 集合中，自动去重
     *
     * @param jsonString 输入的 JSON 字符串
     * @return 包含所有题目标题的字符串集合
     */
    private List<String> extractQuestionTitlesFromOut3(String jsonString) {
        List<String> questionTitles = new ArrayList<>();

        try {
            // 使用 Hutool JSONUtil 解析字符串为 JSONObject
            JSONObject root = JSONUtil.parseObj(jsonString);

            // 获取 out3 对象
            JSONObject out3 = root.getJSONObject("out3");

            // 获取 wrong_questions 数组
            JSONArray wrongQuestions = out3.getJSONArray("wrong_questions");

            // 遍历数组中的每个 JSONObject，提取 questionTitle 字段
            for (int i = 0; i < wrongQuestions.size(); i++) {
                JSONObject question = wrongQuestions.getJSONObject(i);
                if (question.containsKey("questionTitle")) {
                    String title = question.getStr("questionTitle", "").trim();
                    if (!title.isEmpty()) {
                        questionTitles.add(title);
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("解析 JSON 时发生错误: " + e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "解析 JSON 时发生错误: " + e.getMessage());
        }
        return questionTitles;
    }

    /**
     * 计算JSON数据中的总分
     *
     * @param jsonData JSON格式字符串
     * @return 总分
     */
    private int calculateTotalScore(String jsonData) {
        JSONObject jsonObject = JSONUtil.parseObj(jsonData);

        int totalScore = 0;

        // out1
        if (jsonObject.containsKey("out1")) {
            JSONObject output1 = jsonObject.getJSONObject("out1");
            totalScore += output1.getInt("score", 0);
        }

        // out2
        if (jsonObject.containsKey("out2")) {
            JSONObject output2 = jsonObject.getJSONObject("out2");
            totalScore += output2.getInt("score", 0);
        }

        // out3
        if (jsonObject.containsKey("out3")) {
            JSONObject output3 = jsonObject.getJSONObject("out3");
            totalScore += output3.getInt("score", 0);
        }

        return totalScore;
    }

}